package yicheng.dinnertogetherapp;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Date;

import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;











import org.apache.commons.io.FileUtils;

//import com.amazonaws.demo.sdb.SimpleDB;
import yicheng.dinnertogetherapp.R;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.techventus.server.voice.Voice;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

/** 
 * @author Yicheng
 *
 */
public class LogInActivity extends Activity {


	//Twilio account and password, for test app only, security issue should be considered later
	/*	protected static final String ACCOUNT_SID = "ACa8cd84343d08f6f84fd3ca5b1c532751";
	protected static final String AUTH_TOKEN = "dd10c126da38021664352140c022b0a6";*/

	private final String photoFileDirectory = android.os.Environment
			.getExternalStorageDirectory()
			+ File.separator
			+ "Eatogether" + File.separator + "myPhoto" + File.separator;

	private String PHOTO_PATH;




	//UI blocks 
	public static EditText username_input_text, password_input_text, phone_number_input_text, newpassword_input_text, newpassword_second_input_text, nickname_input_text;
	private Button login_button, newuser_button, back_button, register_button, delete_domain_button;
	private Button show_password_button;
	//Button pickdate_button;
	private RelativeLayout logInView, newUserRegisterView, loadingView;
	//TextView birthday_display;





	//Small local database
	private SharedPreferences local_user_information;
	private SharedPreferences.Editor local_user_editor;
	private String PREFS_NAME = "LocalUserInfo";

	private String PRIMARY_PHONE_NUMBER;

	private String PHONE_NUMBER;
	private String NICK_NAME;
	private String PREFERENCE;
	private String START_TIME;
	private String END_TIME;
	private String ONLINE_OFFLINE;

	private String PHOTO_URL;

	public static List<String> domainNames;

	private String sentConfirmationCode;

	//send message thread
	public static Thread sendMessageThread;

	//amazon client manager
	public static AmazonClientManager clientManager;


	private Handler handler;
	private boolean isDataBaseLoaded = false;

	private String passWordInDB;
	private boolean isVerifyProcessComplete = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		//load from shared preference to decide if the user of this phone is already registered
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		boolean notRegistered = local_user_information.getBoolean("notRegistered", true);


		if (notRegistered){

			setContentView(R.layout.login_view);

			//new amazon client manager
			clientManager = new AmazonClientManager();
			//load in loading spinner widget from xml

			loadingView = (RelativeLayout) findViewById(R.id.loading_view_layout);

			loadingView.setVisibility(View.INVISIBLE);

			isDataBaseLoaded = true;

			//domainNames = new ArrayList<String>(StartingViewActivity.domainNames);




			if (isConnectedToInternet()){
				//load in database domain names
				loadDataBase();

			}
			else{
				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LogInActivity.this);
				dialogBuilder.setTitle("Error");
				dialogBuilder.setMessage("You are not connected to Internet, please check.");
				dialogBuilder.setCancelable(true);
				dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which)  {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});

				AlertDialog dialog = dialogBuilder.create();
				dialog.show();
			}



			//Set thread message handler 
			handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					/*		if (msg.what == 1){

						//set true when database is loaded 
						isDataBaseLoaded = true;

						//set loading spinner invisble when database is loaded
						if (isDataBaseLoaded){
							loadingView.setVisibility(View.INVISIBLE);
						}

					}*/
					if(msg.what == 2){
						username_input_text.setText(passWordInDB);
					}

					if(msg.what ==3){
						login();
					}

					if(msg.what == 4){

						Date start_date = new Date();
						try {
							start_date = new SimpleDateFormat("EE, yy/MM/dd h:mm a", Locale.getDefault()).parse(START_TIME);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						Date end_date = new Date();

						try {
							end_date = new SimpleDateFormat("EE, yy/MM/dd h:mm a", Locale.getDefault()).parse(END_TIME);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						String start_year = (String) android.text.format.DateFormat.format("yyyy", start_date);
						String start_month = (String) android.text.format.DateFormat.format("MM", start_date);
						String start_day = (String) android.text.format.DateFormat.format("dd", start_date);
						String start_hour = (String) android.text.format.DateFormat.format("k", start_date);
						String start_min = (String) android.text.format.DateFormat.format("mm", start_date);

						String end_year = (String) android.text.format.DateFormat.format("yyyy", end_date);
						String end_month = (String) android.text.format.DateFormat.format("MM", end_date);
						String end_day = (String) android.text.format.DateFormat.format("dd", end_date);
						String end_hour = (String) android.text.format.DateFormat.format("k", end_date);
						String end_min = (String) android.text.format.DateFormat.format("mm", end_date);

						//Important, format of month has to be subtracted by 1 to be correct in the constructor of Date 
						int int_start_month = Integer.parseInt(start_month) - 1;  
						int int_end_month = Integer.parseInt(end_month) - 1; 


						local_user_editor = local_user_information.edit();



						local_user_editor.remove("start_year");
						local_user_editor.remove("start_month");
						local_user_editor.remove("start_day");
						local_user_editor.remove("start_hour");
						local_user_editor.remove("start_min");

						local_user_editor.remove("end_year");
						local_user_editor.remove("end_month");
						local_user_editor.remove("end_day");
						local_user_editor.remove("end_hour");
						local_user_editor.remove("end_min");
						local_user_editor.commit();


						local_user_editor.putString("start_year", start_year);
						local_user_editor.putString("start_month", String.valueOf(int_start_month));
						local_user_editor.putString("start_day", start_day);
						local_user_editor.putString("start_hour", start_hour);
						local_user_editor.putString("start_min", start_min);

						local_user_editor.putString("end_year", end_year);
						local_user_editor.putString("end_month", String.valueOf(int_end_month));
						local_user_editor.putString("end_day", end_day);
						local_user_editor.putString("end_hour", end_hour);
						local_user_editor.putString("end_min", end_min);




						local_user_editor.putString("Preference", PREFERENCE);
						local_user_editor.putString("start_time", START_TIME);
						local_user_editor.putString("end_time", END_TIME);
						local_user_editor.putString("online_offline", ONLINE_OFFLINE);




						local_user_editor.commit();

						Intent gotoUserMainActivityIntent = new Intent("yicheng.dinnertogetherapp.USERMAINTABVIEWACTIVITY");
						startActivity(gotoUserMainActivityIntent);
						/*finish();*/
						finish();
					}

				}
			};





			//Set initial view to be login view and hide new user register view 
			logInView = (RelativeLayout) findViewById(R.id.logInView_layout);
			newUserRegisterView = (RelativeLayout) findViewById(R.id.newUserRegister_layout);
			logInView.setVisibility(View.VISIBLE);
			newUserRegisterView.setVisibility(View.INVISIBLE);



			//load xml UI into java
			//edit text
			username_input_text = (EditText) findViewById(R.id.username_input_editText);
			password_input_text = (EditText) findViewById(R.id.password_input_editText);
			phone_number_input_text = (EditText) findViewById(R.id.phone_number_input_editText);
			newpassword_input_text = (EditText) findViewById(R.id.newpassword_first_input_editText);
			newpassword_second_input_text = (EditText) findViewById(R.id.newpassword_second_input_editText);
			nickname_input_text = (EditText) findViewById(R.id.nickname_input_editText);

			//button
			login_button = (Button) findViewById(R.id.login_button);
			newuser_button = (Button) findViewById(R.id.newuser_button);
			register_button = (Button) findViewById(R.id.register_button);
			//pickdate_button = (Button) findViewById(R.id.date_picker_button);
			back_button = (Button) findViewById(R.id.back_button);
			delete_domain_button = (Button) findViewById(R.id.delete_domain_button);



			username_input_text.setCursorVisible(false);
			phone_number_input_text.setCursorVisible(false);


			username_input_text.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					username_input_text.setCursorVisible(true);

					username_input_text.requestFocusFromTouch();
					return false;
				}
			});
			/*	username_input_text.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					username_input_text.setCursorVisible(true);

					username_input_text.requestFocusFromTouch();

					//newuser_button.requestFocusFromTouch();
					//username_input_text.requestFocusFromTouch();

				}
			});


			 */

			password_input_text.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					password_input_text.setCursorVisible(true);
					password_input_text.requestFocusFromTouch();
					return false;
				}
			});



			/*password_input_text.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					password_input_text.setCursorVisible(true);
					password_input_text.requestFocusFromTouch();
					//newuser_button.requestFocusFromTouch();
					//password_input_text.requestFocusFromTouch();
				}
			});*/


			phone_number_input_text.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					phone_number_input_text.setCursorVisible(true);
					return false;
				}
			});


			/*	phone_number_input_text.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					phone_number_input_text.setCursorVisible(true);
				}
			});*/


			newpassword_input_text.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub

					newpassword_input_text.setCursorVisible(true);
					return false;
				}
			});


			/*
			newpassword_input_text.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					newpassword_input_text.setCursorVisible(true);
				}
			});*/


			newpassword_second_input_text.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					newpassword_second_input_text.setCursorVisible(true);

					return false;
				}
			});


			/*	newpassword_second_input_text.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					newpassword_second_input_text.setCursorVisible(true);
				}
			});*/


			nickname_input_text.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					nickname_input_text.setCursorVisible(true);
					return false;
				}
			});


			/*	nickname_input_text.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					nickname_input_text.setCursorVisible(true);
				}
			});*/





			password_input_text.setOnEditorActionListener(new OnEditorActionListener(){

				@Override
				public boolean onEditorAction(TextView v, int actionId,
						KeyEvent event) {
					// TODO Auto-generated method stub
					if (actionId == EditorInfo.IME_ACTION_DONE ){
						hideKeyboard();
						final String input_username = username_input_text.getText().toString();
						final String input_password = password_input_text.getText().toString();


						if (input_username.length() >=1 && input_password.length() >=1){

							if (isDataBaseLoaded){

								//Check if cliendManager is the valid one 
								if (clientManager.hasCredentials()){

									//Check if the phone has access to Internet
									if (isConnectedToInternet()){

										verifyUser();


										/*	runOnUiThread(new Runnable(){

								public void run() {

									Thread verifyUserThread = new Thread(new Runnable(){

										public void run() {
											// TODO Auto-generated method stub
											verifyUser(input_username, input_password);
										}

									});

									verifyUserThread.run();
								}

							});*/

									}
									else{
										Toast.makeText(LogInActivity.this, "You are not connected to network, please check", Toast.LENGTH_SHORT).show();
									}
								}
								else{
									Toast.makeText(LogInActivity.this, "Database cridential is wrong", Toast.LENGTH_SHORT).show();
								}
							}
							else{
								Toast.makeText(LogInActivity.this, "Loading data, please wait.", Toast.LENGTH_SHORT).show();
							}
						}
						else{
							Toast.makeText(LogInActivity.this, "Phone number or password is empty, please check.", Toast.LENGTH_SHORT).show();
						}

					}
					return false;
				}

			});



			//dismiss keyboard when touch outside of the textview
			logInView.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					username_input_text.setCursorVisible(false);
					password_input_text.setCursorVisible(false);
					hideKeyboard();
					return false;
				}
			});


			newUserRegisterView.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub

					loadingView.setVisibility(View.INVISIBLE);		
					phone_number_input_text.setCursorVisible(false);
					newpassword_input_text.setCursorVisible(false);
					newpassword_second_input_text.setCursorVisible(false);
					nickname_input_text.setCursorVisible(false);
					hideKeyboard();
					return false;

				}
			});






			//Login button action
			login_button.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					hideKeyboard();
					final String input_username = username_input_text.getText().toString();
					final String input_password = password_input_text.getText().toString();


					if (input_username.length() >=1 && input_password.length() >=1){

						if (isDataBaseLoaded){

							//Check if cliendManager is the valid one 
							if (clientManager.hasCredentials()){

								//Check if the phone has access to Internet
								if (isConnectedToInternet()){

									verifyUser();


									/*	runOnUiThread(new Runnable(){

							public void run() {

								Thread verifyUserThread = new Thread(new Runnable(){

									public void run() {
										// TODO Auto-generated method stub
										verifyUser(input_username, input_password);
									}

								});

								verifyUserThread.run();
							}

						});*/

								}
								else{
									Toast.makeText(LogInActivity.this, "You are not connected to network, please check", Toast.LENGTH_SHORT).show();
								}
							}
							else{
								Toast.makeText(LogInActivity.this, "Database cridential is wrong", Toast.LENGTH_SHORT).show();
							}
						}
						else{
							Toast.makeText(LogInActivity.this, "Loading data, please wait.", Toast.LENGTH_SHORT).show();
						}
					}
					else{
						Toast.makeText(LogInActivity.this, "Phone number or password is empty, please check.", Toast.LENGTH_SHORT).show();
					}


				}
			});



			//Set new user button action
			newuser_button.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					hideKeyboard();
					//Show new user register view and hide login view
					Animation animationFadeIn = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fade_out);
					logInView.startAnimation(animationFadeIn);
					logInView.setVisibility(View.INVISIBLE);

					Handler handler = new Handler(); 
					handler.postDelayed(new Runnable() { 
						public void run() { 
							Animation animationLeftIn = AnimationUtils.loadAnimation(getBaseContext(), R.anim.activity_left_in);
							newUserRegisterView.startAnimation(animationLeftIn);
							newUserRegisterView.setVisibility(View.VISIBLE);

						} 
					}, 300); 


					/*	Animation animationLeftIn = AnimationUtils.loadAnimation(getBaseContext(), R.anim.activity_left_in);
					newUserRegisterView.startAnimation(animationLeftIn);
					newUserRegisterView.setVisibility(View.VISIBLE);
					 */

					username_input_text.setText(null);
					password_input_text.setText(null);



				}
			});



			//Set back button action in new user register view
			back_button.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					hideKeyboard();

					AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LogInActivity.this);
					dialogBuilder.setTitle("Exit");

					dialogBuilder.setMessage("Information you entered will not be kept, sure to exit?");
					dialogBuilder.setCancelable(true);
					dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							//Clear user input in new user register view
							clearRegisterInput();
							dialog.cancel();

							//Show login view and hide new user register view

							Animation animationFadeIn = AnimationUtils.loadAnimation(getBaseContext(), R.anim.activity_right_out);
							newUserRegisterView.startAnimation(animationFadeIn);

							newUserRegisterView.setVisibility(View.INVISIBLE);
							Handler handler = new Handler(); 
							handler.postDelayed(new Runnable() { 
								public void run() { 
									Animation animationFadeIn = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fade_in);
									logInView.startAnimation(animationFadeIn);
									logInView.setVisibility(View.VISIBLE);
								} 
							}, 100); 


						}
					});

					dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							dialog.cancel();

						}
					});

					AlertDialog dialog = dialogBuilder.create();
					dialog.show();

				}
			});



			//Set pick date button action
			/*		pickdate_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Calendar calendar = Calendar.getInstance();
				int year = calendar.get(Calendar.YEAR);
				int month = calendar.get(Calendar.MONTH);
				int day = calendar.get(Calendar.DAY_OF_MONTH);

				DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int selectedYear, int selectedMonth,
							int selectedDay) {

						int year;
						int month;
						int day;
						// TODO Auto-generated method stub
						year = selectedYear;
						month = selectedMonth;
						day = selectedDay;

						birthday_display.setText(month+ "/" + day + "/" + year);

					}
				};


				DatePickerDialog datePickerDialog = new DatePickerDialog(LogInActivity.this, dateSetListener, year, month, day);

				datePickerDialog.show();

			}
		});*/


			//Set register button action
			register_button.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					hideKeyboard();
					if (isRegisterInfoValid()){
						if (isDataBaseLoaded){
							int randomNum = (int)(Math.random()*10000) + 1000;			
							if (randomNum / 10000 >= 1){
								randomNum = randomNum - 1000;
							}
							if (randomNum == 10000){
								randomNum = 9999;
							}

							/*sentConfirmationCode = "" + randomNum;*/

							sentConfirmationCode = "1234";

							AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LogInActivity.this);
							dialogBuilder.setTitle("Confirmation");


							dialogBuilder.setMessage("We have sent you a text message with confirmation code.");
							dialogBuilder.setCancelable(true);
							dialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which)  {
									// TODO Auto-generated method stub
									dialog.cancel();

									//Put new user phone number, password, nickname into bundle and pass it to the confirmation code activity
									Bundle data_bundle = new Bundle();
									data_bundle.putString("PhoneNumber", phone_number_input_text.getText().toString());
									data_bundle.putString("Password", newpassword_input_text.getText().toString());
									data_bundle.putString("Nickname", nickname_input_text.getText().toString());
									data_bundle.putString("GeneratedConfirmationCode", sentConfirmationCode);

									//Start confirmation code activity
									Intent openConfirmationCodeIntent = new Intent("yicheng.dinnertogetherapp.CONFIRMATIONCODEACTIVITY");
									openConfirmationCodeIntent.putExtra("RegisterInformaionData", data_bundle);
									startActivity(openConfirmationCodeIntent);
									finish();


									sendMessageThread = new Thread(new Runnable(){
										@Override
										public void run() {

											/*	try {
												sendMessage();
											} catch (IOException e) {

												e.printStackTrace();
											}*/

										}

									});

									sendMessageThread.start();


								}
							});

							dialogBuilder.setCancelable(false);

							AlertDialog dialog = dialogBuilder.create();
							dialog.show();
						}
						else{
							Toast.makeText(LogInActivity.this, "Loading data, please wait.", Toast.LENGTH_SHORT).show();
						}

					}
					else{
						AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LogInActivity.this);
						dialogBuilder.setTitle("Wrong information");

						if (!isInputInfoNotNull()){
							dialogBuilder.setMessage("One or more of your information is empty, please check.");

						}
						else if  (!isInputPasswordTheSame()){
							dialogBuilder.setMessage( "The password you input are not the same, please check.");
						}
						else if (isPhoneNumberIntheDatabase()){
							if(isDataBaseLoaded){
								dialogBuilder.setMessage( "The phone number you input is already registered, please log in.");
							}
							else{
								Toast.makeText(LogInActivity.this, "Loading data, please wait.", Toast.LENGTH_SHORT).show();
							}

						}



						dialogBuilder.setCancelable(true);
						dialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {

								dialog.cancel();
							}
						});

						AlertDialog dialog = dialogBuilder.create();
						dialog.show();

					}

				}
			});



			delete_domain_button.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					if (domainNames.contains(phone_number_input_text.getText().toString())){
						runOnUiThread(new Runnable(){


							public void run() {

								Thread setupDBThread = new Thread(new Runnable(){

									public void run() {

										SimpleDB.deleteDomain(clientManager, phone_number_input_text.getText().toString());

										//Toast.makeText(ConfirmationCodeActivity.this, "error loading database", Toast.LENGTH_SHORT).show();





									}

								});

								setupDBThread.start();
							}	
						});
					}
					else{
						Toast.makeText(LogInActivity.this, "the number is not in the database", Toast.LENGTH_SHORT).show();
					}
				}
			});

			/*	getCode_button.setText("Get Code");

		final CountDownTimer timer = new CountDownTimer(10000, 1000){

			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub
				getCode_button.setText(""+millisUntilFinished/1000);
			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				getCode_button.setText("Get Code");
			}

		};
			 */

			/*if (getCode_button.getText().toString() != "Get Code"){
			getCode_button.setClickable(false);
		}*/

			/*	getCode_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				String input_phoneNumber = phone_number_input_text.getText().toString();
				String first_input_password = newpassword_input_text.getText().toString();
				String second_input_password = newpassword_second_input_text.getText().toString();
				String input_confirmationCode = confirmationCode_text.getText().toString();


				if (getCode_button.getText().toString() == "Get Code" ){


				timer.start();

				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LogInActivity.this);
				dialogBuilder.setTitle("Confirmation Code");

				dialogBuilder.setMessage("The confirmation code is texted to your phone, please check.");
				dialogBuilder.setCancelable(true);
				dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();

					}
				});

				AlertDialog dialog = dialogBuilder.create();

				dialog.show();


				}
			}
		});*/







			show_password_button = (Button) findViewById(R.id.show_password_button);


			show_password_button.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					if (domainNames.contains(username_input_text.getText().toString())){
						runOnUiThread(new Runnable(){

							@Override
							public void run() {
								// TODO Auto-generated method stub
								new Thread(new Runnable(){

									@Override
									public void run() {
										// TODO Auto-generated method stub
										passWordInDB = SimpleDB.getSingleAttributesForItem(clientManager, username_input_text.getText().toString(), "passwordItem", "userPassword");


										Message msg = Message.obtain();
										msg.what = 2;
										handler.sendMessage(msg);

									}

								}).start();

							}

						});


					}
					else{
						Toast.makeText(getApplicationContext(), "the phone number is not in the database", Toast.LENGTH_SHORT).show();
					}



				}
			});

		}
		else{
			Intent gotoUserMainActivity = new Intent("yicheng.dinnertogetherapp.USERMAINTABVIEWACTIVITY");
			startActivity(gotoUserMainActivity);

			finish();

		}
	}



	//send SMS message to the input phone number 
	private void sendMessage() throws IOException{
		Voice voice = new Voice("zhangyicheng1234@gmail.com","83251209");
		voice.login();
		String phoneNumber = phone_number_input_text.getText().toString();
		voice.sendSMS(phoneNumber, "Your Eat2gether verification code is:  " + sentConfirmationCode + "  Please confirm.");
	}


	//Check if input new user register information is valid
	private boolean isRegisterInfoValid(){
		return isInputPasswordTheSame()  && isInputInfoNotNull() && !isPhoneNumberIntheDatabase();
	}


	//If the input new user phone number in the database
	private boolean isPhoneNumberIntheDatabase(){
		if (isDataBaseLoaded){
			return domainNames.contains(phone_number_input_text.getText().toString());	
		}
		else{
			return false;
		}
	}

	//If the two input passwords are the same
	private boolean isInputPasswordTheSame(){
		return newpassword_input_text.getText().toString().equals(newpassword_second_input_text.getText().toString());
	}

	//If all the information is filled 
	private boolean isInputInfoNotNull(){
		return phone_number_input_text.getText().toString().length() >= 1 && newpassword_input_text.getText().toString().length() >= 1 && newpassword_second_input_text.getText().toString().length() >= 1 && nickname_input_text.getText().toString().length() >= 1; 
	}


	//Clear new user input information
	private void clearRegisterInput(){
		phone_number_input_text.setText(null);
		newpassword_input_text.setText(null);
		newpassword_second_input_text.setText(null);
		nickname_input_text.setText(null);
		//birthday_display.setText("mm/dd/yy");
	}


	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		moveTaskToBack(true);
	}



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK ) {
			//preventing default implementation previous to 
			//android.os.Build.VERSION_CODES.ECLAIR
			moveTaskToBack(true);

			return false;
		}     
		return super.onKeyDown(keyCode, event);    

	}




	//Check if the login username and login password are correct
	private void verifyUser(){
		/*domainNames = SimpleDB.getDomainNames();*/



		if (domainNames.contains(username_input_text.getText().toString())){

			runOnUiThread(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					new Thread(new Runnable(){

						@Override
						public void run() {
							// TODO Auto-generated method stub
							passWordInDB = SimpleDB.getSingleAttributesForItem(clientManager, username_input_text.getText().toString(), SimpleDB.PASSWORD_ITEM, SimpleDB.PASSWORD_ATTRIBUTE);

							NICK_NAME = SimpleDB.getSingleAttributesForItem(clientManager, username_input_text.getText().toString(), SimpleDB.NICKNAME_ITEM, SimpleDB.NICKNAME_ATTRIBUTE);



							Message msg = Message.obtain();
							msg.what = 3;
							handler.sendMessage(msg);

						}

					}).start();
				}

			});







		}
		else{
			AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LogInActivity.this);
			dialogBuilder.setTitle("Wrong login information");

			dialogBuilder.setMessage("The phone number you entered is not registered yet.");
			dialogBuilder.setCancelable(true);
			dialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method st
					dialog.cancel();
				}
			});

			AlertDialog dialog = dialogBuilder.create();

			dialog.show();

		}

	}





	//Check if the device is connected to Internet
	private boolean isConnectedToInternet(){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)LogInActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi_network = 
				connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mobile_network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);


		return wifi_network.isConnectedOrConnecting() || mobile_network.isConnectedOrConnecting();

		/*return mobile_network.isConnectedOrConnecting();*/
	}



	/*private class loadDataBase extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... Void) {
			// TODO Auto-generated method stu
			loadingSpinner.setVisibility(View.VISIBLE);
			domainNames = SimpleDB.getDomainNames(clientManager);


			//loadingSpinner.setVisibility(View.VISIBLE);


				}
			catch (NullPointerException e){
				Toast.makeText(getApplicationContext(), "Your connection to Internet has problem, please check.", Toast.LENGTH_SHORT).show();
			}
			Message msg = Message.obtain();
			msg.what = 1;
			handler.sendMessage(msg);
			//return null;
			return null;
		}
	}
	 */

	private void loadDataBase(){
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						domainNames = SimpleDB.getDomainNames(clientManager);


						//loadingSpinner.setVisibility(View.VISIBLE);


						/*	}
						catch (NullPointerException e){
							Toast.makeText(getApplicationContext(), "Your connection to Internet has problem, please check.", Toast.LENGTH_SHORT).show();
						}*/
						Message msg = Message.obtain();
						msg.what = 1;
						handler.sendMessage(msg);

					}

				}).start();
			}

		});

	}



	private void hideKeyboard(){
		if(getCurrentFocus()!=null) {
			InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
		}
	}

	/*protected void onPostExecute(Void result){
			Toast.makeText(LogInActivity.this, "loading data base", Toast.LENGTH_SHORT).show();
		}*/



	private void login(){
		if (passWordInDB.equals(password_input_text.getText().toString())){

			Toast.makeText(getApplicationContext(), "login success", Toast.LENGTH_SHORT).show();

			local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
			local_user_editor = local_user_information.edit();

			local_user_editor.putBoolean("notRegistered", false);
			local_user_editor.putString("PhoneNumber", username_input_text.getText().toString());
			local_user_editor.putString("Password", password_input_text.getText().toString());
			local_user_editor.putString("Nickname", NICK_NAME);

			local_user_editor.commit();


			updatePreferenceAndAvailability();




		}
		else{
			AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LogInActivity.this);
			dialogBuilder.setTitle("Wrong login information");

			dialogBuilder.setMessage("The password you entered is not correct, please check");
			dialogBuilder.setCancelable(true);
			dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method st
					dialog.cancel();
				}
			});

			AlertDialog dialog = dialogBuilder.create();

			dialog.show();
		}
	}
	/*protected void onPostExecute(Void result) {
			updateUi(domainNames, SUCCESS);
		}*/



	private void updatePreferenceAndAvailability(){
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");


		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						PREFERENCE = SimpleDB.getSingleAttributesForItem(clientManager,username_input_text.getText().toString(), SimpleDB.PREFERENCE_ITEM, SimpleDB.PREFERENCE_ATTRIBUTE);
						START_TIME = SimpleDB.getSingleAttributesForItem(clientManager, username_input_text.getText().toString(), SimpleDB.AVAILABILITY_ITEM, SimpleDB.START_TIME_ATTRIBUTE);
						END_TIME = SimpleDB.getSingleAttributesForItem(clientManager, username_input_text.getText().toString(), SimpleDB.AVAILABILITY_ITEM, SimpleDB.END_TIME_ATTRIBUTE);
						ONLINE_OFFLINE = SimpleDB.getSingleAttributesForItem(clientManager, username_input_text.getText().toString(), SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE);


						PHOTO_URL = SimpleDB.getSingleAttributesForItem(clientManager, username_input_text.getText().toString(), SimpleDB.PHOTO_URL_ITEM, SimpleDB.PHOTO_URL_ATTRIBUTE);




						downLoadPhotoFromS3();






						Message msg = Message.obtain();
						msg.what = 4;
						handler.sendMessage(msg);

					}

				}).start();
			}

		});








	}



	private void downLoadPhotoFromS3(){

		// TODO Auto-generated method stub
		/*	AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials( PropertyLoader.getInstance().getAccessKey(), PropertyLoader.getInstance().getSecretKey() ) );      

		List<Bucket> listOfBucket = s3Client.listBuckets();

		Bucket photo_bucket = listOfBucket.get(2);


		URL currentUrl = s3Client.getUrl(photo_bucket.getName(), PHONE_NUMBER);*/




		//Toast.makeText(getBaseContext(), currentUrl.toString(), Toast.LENGTH_LONG).show();

		Log.d("url in databse ", PHOTO_URL);
		
		

		File file = new File(photoFileDirectory,  "myPhoto.jpg");

		try {
			FileUtils.copyURLToFile(new URL(PHOTO_URL), file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();


		}


		local_user_editor = local_user_information.edit();
		local_user_editor.putString("PhotoPath", photoFileDirectory +"myPhoto.jpg");
		local_user_editor.commit();

		/*	Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		Uri contentUri = Uri.fromFile(file);
		mediaScanIntent.setData(contentUri);
		sendBroadcast(mediaScanIntent);*/

		/*
			File file = new File(photoFileDirectory,  "myPhoto.jpg");
			s3Client.getObject(new GetObjectRequest(photo_bucket.getName(), PHONE_NUMBER), file);



			local_user_editor = local_user_information.edit();
			local_user_editor.putString("PhotoPath", photoFileDirectory +"myPhoto.jpg");
			local_user_editor.commit();



			Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			Uri contentUri = Uri.fromFile(file);
			mediaScanIntent.setData(contentUri);
			sendBroadcast(mediaScanIntent);*/


		/*}*/



	}



}
